# frozen_string_literal: true

ActiveAdmin.register Rule do
  # config.create_another = true
  menu parent: ['Rules Engine'], priority: 1

  # config.per_page = [10, 50, 100]

  # sidebar :help do
  #   'Need help? Email us at help@example.com'
  # end

  permit_params :type,
                :name,
                :description,
                draft_entity_attributes: [
                  :id, :rule_id, :type, :policy,
                  rule_schema_attributes: %i[id rule_entity_id schema_id]
                ],
                # entities_attributes: %i[id rule_id type policy _destroy],
                comment_attributes: %i[id body _destroy]

  # permit_params do
  #   permitted = %i[uuid name type description draft_entity]
  #   permitted
  # end

  includes :draft_entity

  index do
    # selectable_column
    id_column
    # column 'UUID', :uuid
    column 'UUID' do |rule|
      link_to rule.uuid, admin_rule_path(rule)
    end
    column 'Rule Type', :type
    column 'Name', :name
    column 'Status', 'status'
    column 'Description', :description

    column 'Draft' do |rule|
      entity = rule.draft
      link_to 'draft', admin_rule_entity_path(entity) if entity
    end
    column 'Current' do |rule|
      entity = rule.current
      link_to "V-#{entity.version}", admin_rule_entity_path(entity) if entity
    end

    actions
  end

  filter :name, filters: %i[equals contains]
  filter :type, as: :select, collection: proc { [Rule::GeneralRule, Rule::DecisionTable, Rule::RuleSet] }
  filter :status, as: :select, collection: proc { Rule::Status.values }
  filter :description

  form remote: false do |f|
    f.semantic_errors(*f.object.errors.keys)

    f.inputs 'Basic Details' do
      f.input :type, as: :select, collection: [Rule::GeneralRule, Rule::DecisionTable, Rule::RuleSet]
      f.input :name
      f.input :description, as: :text
    end

    # entity_types = {
    #   Rule::GeneralRule => [
    #     RuleEntity::GeneralRule::Dsl,
    #     RuleEntity::GeneralRule::Condition::All,
    #     RuleEntity::GeneralRule::Condition::Any,
    #     RuleEntity::GeneralRule::Condition::Dsl
    #   ],
    #   Rule::DecisionTable => [RuleEntity::DecisionTable],
    #   Rule::RuleSet => [RuleEntity::RuleSet]
    # }
    # f.inputs name: 'Entity Detail', for: :draft_entity do |ef|
    #   ef.input :type, as: :select, collection: (rule.type ? entity_types[rule.type] : entity_types.values.flatten)
    #   ef.input :policy, as: :select, collection: RuleEntity::Policy.values
    #   f.input :schema, as: :select, input_html: { class: 'select2' }
    #
    #   # f.semantic_fields_for :rule_schema do |rf|
    #   #   rf.input :schema, as: :select
    #   # end
    #   # ef.inputs :schema, for: :rule_schema, name: 'Schema'
    #   # byebug
    #   # ef.inputs name: 'Schema', for: :rule_schema do |sf|
    #   #   sf.input :schema
    #   #   # ef.input :type
    #   # end
    #   # ef.inputs do
    #   #   ef.has_many :rule_schema do |sf|
    #   #     sf.input :schema
    #   #   end
    #   # end
    #
    #   # ef.inputs do
    #   #   ef.has_many :rule_schema, name: 'Rule Schema', allow_destroy: true do |sf|
    #   #     sf.input :schema, as: :select
    #   #   end
    #   # end
    # end

    # f.inputs do
    #   f.has_many :draft_entity, new_record: 'Draft entity', allow_destroy: false do |df|
    #     df.input :type, as: :select, collection: (entity_types[rule.type || Rule::GeneralRule])
    #     df.input :policy
    #     # df.input 'Schema' do |entity|
    #     # df.input :schema, input_html: { class: 'select2' }
    #   end
    # end

    f.actions
  end

  controller do
    # def create
    #   @result = RuleService.create(params.require(:rule))
    #   if @result[:code].zero?
    #     render admin_rule_path(@result[:rule]['id'])
    #   else
    #     respond_to do |format|
    #       format.js
    #       format.json { render json: @result }
    #     end
    #   end
    # end
  end

  # collection_action :index, method: :get do
  #   # Do some CSV importing work here...
  #   # byebug
  #   # puts "+++++++++++++++++++++++++++++++++++++++++"
  #   # redirect_to collection_path, notice: "CSV imported successfully!"
  #   # byebug
  #   # renderer_for :index
  # end

  action_item :terminate_membership, only: :show do
    link_to 'New Entity', new_admin_rule_entity_path(rule_id: rule) if rule.entities.empty?
  end
  action_item :draft_decision_table, only: :show do
    link_to 'Draft Decision Table', admin_rule_draftdecisiontable_path(rule) if rule.entities.empty?
  end

  show do
    attributes_table do
      row :name
      row :description
      row :uuid
      row :current_version
      row :status
      row :created_at
      row :updated_at
    end

    # table_actions :add_entity, method: :get do
    #   # ...
    #   redirect_to admin_rule_entity_path, notice: "Your event was added"
    # end
    # action_items do
    #   link_to "View Site", "/"
    # end

    panel 'All Entities' do
      # byebug
      if rule.entities.empty?
        button_to(
          'New Entity',
          admin_rule_entity_path(rule: rule)
          # remote: true,
          # data: { confirm: 'Are you sure?', disable_with: 'loading...' },
          # class: 'rule-entity-deploy'
        )
      end

      entities = rule.entities.update_desc.page(params[:page]).per(5)

      paginated_collection(entities, download_links: false) do
        table_for entities do
          column 'ID' do |entity|
            link_to entity.id, admin_rule_entity_path(entity)
          end
          column :type
          column :status
          column :stage
          column :policy
          column :version
          column :created_at
          column :updated_at

          column 'Actions' do |entity|
            if entity.status.eql?(RuleEntity::Status::CREATED)
              span class: 'inline-span' do
                button_to(
                  'Validate',
                  validate_rule_entity_path(entity),
                  remote: true,
                  data: { disable_with: 'loading...' },
                  class: 'rule-entity-validate'
                )
              end
            end

            if entity.draft?
              span class: 'inline-span' do
                button_to(
                  'Deploy',
                  deploy_rule_entity_path(entity),
                  remote: true,
                  data: { confirm: 'Are you sure?', disable_with: 'loading...' },
                  class: 'rule-entity-deploy'
                )
              end
            end

            # span class: 'inline-span' do
            #   button_to(
            #     'Fire',
            #     rule_entities_fire_path(id: entity.id, inputs: {}),
            #     remote: true,
            #     form: { 'data-type' => 'json' },
            #     data: { confirm: 'Are you sure?', disable_with: 'loading...' }
            #   )
            # end
          end
        end
      end
    end

    panel 'All Version' do
      versions = rule.versions.version_desc.page(params[:page]).per(5)
      paginated_collection(versions, download_links: false) do
        table_for versions do
          column :version
          column :start_time
          column :end_time
          column :created_at
          column :updated_at
        end
      end
    end
  end
end
